let FIXED_CLASSTIME;
let tableHtml = '<table class="table table-bordered"><thead><tr><th>时段</th><th>节次</th><th>开始时间</th><th>结束时间</th><th>操作</th></tr></thead><tbody>';
let firstOcation=true;
$(document).ready(function () {
    // 页面加载时初始化表格
    updateTable();

    // 监听时段选择、课程时间和休息时间的变化
    $('#div-daytime input[type="checkbox"]').on('change', updateTable);
    $('#c-classtime, #c-classsleeptime').on('input', updateTable);


    // 绑定动态添加的按钮事件
    $('#schedule-table-container').on('click', '.add-class', function (event) {
        event.stopPropagation(); // 阻止事件冒泡
        event.preventDefault();  // 阻止默认行为
        const row = $(this).closest('tr');
        const newRow = row.clone();

        oldstartTime = row.find('.start-time').val();
        oldendTime = row.find('.end-time').val();
        FIXED_CLASSTIME = parseInt($('#c-classtime').val(), 10);
        const classsleeptime = parseInt($('#c-classsleeptime').val(), 10);
        if (oldstartTime && !isNaN(FIXED_CLASSTIME) && !isNaN(classsleeptime)) {
            startTime = calculateEndTime(oldendTime, classsleeptime);
            endTime = calculateEndTime(startTime, FIXED_CLASSTIME);
        }
        newRow.find('.start-time').val(startTime);
        newRow.find('.end-time').val(endTime);
        row.after(newRow);
        // 重新按顺序改变排课节次号码
        let rowIndex = 1;
        $('#schedule-table-container tr').each(function () {
            if ($(this).find('.oindex').length > 0) {
                $(this).find('.oindex').val(rowIndex);
                rowIndex++;
            }

        });
        $("#maxks").trigger("click");
        saveScheduleData();
    });

    $('#schedule-table-container').on('click', '.remove-class', function (event) {
        event.stopPropagation(); // 阻止事件冒泡
        event.preventDefault();  // 阻止默认行为

        const row = $(this).closest('tr');
        if ($('#schedule-table-container tr').length > 2) { // 至少保留一行
            row.remove();
        } else {
            alert('至少需要保留一行！');
        }
        // 重新按顺序改变排课
        let rowIndex = 1;
        $('#schedule-table-container tr').each(function () {
            if ($(this).find('.oindex').length > 0) {
                $(this).find('.oindex').val(rowIndex);
                rowIndex++;
            }
        });
        $("#maxks").trigger("click");
        saveScheduleData();
    });

    $('#schedule-table-container').on('input', '.start-time, .class-count', function () {
        const row = $(this).closest('tr');
        const startTime = row.find('.start-time').val();
        const classsleeptime = parseInt($('#c-classsleeptime').val(), 10);
        FIXED_CLASSTIME = parseInt($('#c-classtime').val(), 10);
        if (startTime && !isNaN(FIXED_CLASSTIME) && !isNaN(classsleeptime)) {
            const endTime = calculateEndTime(startTime, FIXED_CLASSTIME);
            row.find('.end-time').val(endTime);
        }
    });
});

function updateTable() {

    const selectedDaytimes = $('#div-daytime input[type="checkbox"]:checked').map(function () {
        // 获取每个选中的复选框后面的文本内容
        return $(this).parent().text().trim();
    }).get();

    const classtime = parseInt($('#c-classtime').val(), 10);
    const classsleeptime = parseInt($('#c-classsleeptime').val(), 10);

    // 如果时段未选择或课程时间/休息时间未填写，清空表格
    if (!selectedDaytimes.length || isNaN(classtime) || isNaN(classsleeptime)) {
        $('#schedule-table-container').html('');
        return;
    }
    // 生成表格
    setTimeout(function () {
        if (row && row['schedule_data']&&firstOcation) {
            loadScheduleData();
            firstOcation=false;
        } else {
            if($("#table-bordered>tr").length>1){
                temp = tableHtml;
                var aldaytimes = $('.table-bordered').find("input[name=daytime]").map(function() {
                    return $(this).val();
                }).get();
                selectedDaytimes.forEach((daytime, index) => {
                    if(!aldaytimes.includes(daytime)){
                     temp += `
        <tr>
            <td><input type="text" name="daytime" class="form-control" value="${daytime}" style="width:60px" /></td>
            <td><input type="text" name="oindex" class="form-control oindex" value="${index + 1}" style="width:40px" /></td> <!-- 默认课节为1 -->
            <td><input type="time" class="form-control start-time" name="start_time" /></td>
            <td><input type="time" class="form-control end-time" name="end_time" readonly /></td>
            <td>
                <button class="btn btn-sm btn-success add-class">+</button>
                <button class="btn btn-sm btn-danger remove-class">-</button>
            </td>
        </tr>
    `;
                    }
                });
            }else {
                temp = tableHtml;
                selectedDaytimes.forEach((daytime, index) => {
                    temp += `
        <tr>
            <td><input type="text" name="daytime" class="form-control" value="${daytime}" style="width:60px" /></td>
            <td><input type="text" name="oindex" class="form-control oindex" value="${index + 1}" style="width:40px" /></td> <!-- 默认课节为1 -->
            <td><input type="time" class="form-control start-time" name="start_time" /></td>
            <td><input type="time" class="form-control end-time" name="end_time" readonly /></td>
            <td>
                <button class="btn btn-sm btn-success add-class">+</button>
                <button class="btn btn-sm btn-danger remove-class">-</button>
            </td>
        </tr>
    `;
                });
            }
            temp += '</tbody></table>';
            $('#schedule-table-container').html(temp);
        }
    }, 500);
}



function calculateEndTime(startTime, classtime) {
    const [startHour, startMinute] = startTime.split(':').map(Number);
    let totalMinutes = startHour * 60 + startMinute;
    totalMinutes += classtime;
    const endHour = Math.floor(totalMinutes / 60) % 24;
    const endMinute = totalMinutes % 60;
    return `${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}`;
}


function saveScheduleData() {
    var tableData = [];
    $('#schedule-table-container tr:gt(0)').each(function (key, value) {
        var rowData = {
            daytime: $(this).find('input[name=daytime]').val(),
            oindex: $(this).find('input[name=oindex]').val(),
            start_time: $(this).find('input[name="start_time"]').val(),
            end_time: $(this).find('input[name="end_time"]').val(),
        };
        tableData.push(rowData);
    });

    // 将表格数据转换为 JSON 字符串并存储在隐藏字段中
    $('#schedule-data').val(JSON.stringify(tableData));
}

$('#schedule-table-container').on('input blur', 'input, select', function () {
    // 当表格数据发生变化时，保存表格数据
    saveScheduleData();
});


// 在编辑页面加载时，从 JSON 数据中还原表格
function loadScheduleData() {
    var jsonData = $('#schedule-data').val();
    if (jsonData) {
        var tableData = JSON.parse(jsonData);
        let tableHtml2 = '';
        tableData.forEach(function (rowData) {
            tableHtml2 += `
            <tr>
                <td><input type="text" name="daytime" class="form-control" value="${rowData.daytime}" style="width:60px" /></td>
                <td><input type="text" name="oindex" class="form-control oindex" value="${rowData.oindex}" style="width:40px" /></td> <!-- 默认课节为1 -->
                <td><input type="time" class="form-control start-time" name="start_time" value="${rowData.start_time}" /></td>
                <td><input type="time" class="form-control end-time" name="end_time" value="${rowData.end_time}" readonly /></td>
                <td>
                    <button class="btn btn-sm btn-success add-class">+</button>
                    <button class="btn btn-sm btn-danger remove-class">-</button>
                </td>
            </tr>
        `;
        });
        $('#schedule-table-container').append(""+tableHtml + tableHtml2+"</table>");
        if (tableData.length < 1) {
            updateTable();
        }
    }
}



